package com.newer.web.controller;

import com.newer.dto.MsgDto;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 周叶云
 * @date 2022/5/12 15:05
 * @description:
 **/

@RestController
@RequestMapping("upload")
public class UploadController {

    @RequestMapping("upload")
    public MsgDto upload(String title, MultipartFile imgname, HttpSession session) throws IOException {

//保存到当前工程目录下
        if(imgname!=null && imgname.getSize()>0) {
            //1.得到发布之后的绝对路径
            String realpath="D:/warehouse/upload";

            //2.根据当前日期创建文件夹（如果存在，忽略)
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            String dir=sdf.format(new Date());
            File file=new File(realpath+"/"+dir);
            if(!file.exists()) {
                file.mkdir();
            }

            //3.产生一个随机的文件名
            String oldName=imgname.getOriginalFilename();
            String fileName= UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."));

            String path=realpath+"/"+dir+"/"+fileName;

            //实现文件的复制
            imgname.transferTo(new File(path));

            String url="Upload/"+dir+"/"+fileName;


         return new MsgDto(true,url);
        }
        return new MsgDto(false,"上传失败");
    }
}
